<template>
  <BaseDialog
    v-model="dialogVisible"
    :title="title"
    width="1100px"
    :before-close="handleClose"
  >
    <el-form
      ref="refDialogForm"
      v-loading="formLoading"
      class="set-dialog-form"
      :label-width="language === 'en' ? '180px' : '94px'"
      :model="formData"
      :rules="rules"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('device.deviceModel')" prop="model">
            <BaseSelect
              v-model="formData.model"
              :options="deviceModelList"
              :label="$t('device.deviceModel')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="外设类型" prop="type">
            <BaseSelect
              v-model="formData.type"
              :options="peripheralModelList"
              label="外设类型"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="外设名称" prop="name">
            <TextInput v-model="formData.name" label="外设名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="外设标签" prop="tag">
            <TextInput v-model="formData.tag" label="外设标签" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="外设驱动ID" prop="driverId">
            <TextInput v-model="formData.driverId" label="外设驱动ID" />
          </el-form-item>
        </el-col>
        <el-col
          v-if="
            formData.type === '6' ||
            formData.type === '7' ||
            formData.type === '8'
          "
          :span="24"
        >
          <el-form-item style="margin-bottom: 0" required>
            <template #label>
              <label>动作列表</label>
            </template>
            <el-button
              type="primary"
              style="margin-bottom: 10px"
              @click="handleAddAction"
              >{{ $t('public.add') }}</el-button
            >
          </el-form-item>
        </el-col>
        <el-col
          v-if="
            formData.type === '6' ||
            formData.type === '7' ||
            formData.type === '8'
          "
          :span="24"
        >
          <el-form-item
            label-width="0"
            class="form-item-table"
            prop="actionList"
          >
            <BaseTable
              ref="refContentTable"
              v-loading="tableLoading"
              :data="formData.actionList"
              row-key="id"
            >
              <TableColumn
                prop="label"
                label="动作名称"
                :column-width="columnWidthObj.label"
              />
              <TableColumn
                prop="value"
                label="动作ID"
                :column-width="columnWidthObj.value"
              />
              <TableColumn
                prop="action"
                fixed="right"
                :label="$t('public.action')"
                :column-width="columnWidthObj.action"
              >
                <template #default="{ row, $index }">
                  <!-- <el-button
                    text
                    :disabled="$index === 0"
                    @click="handleActionMoveUp(row, $index)"
                  >
                    {{ $t('recipe.moveUp') }}
                  </el-button>
                  <el-button
                    text
                    :disabled="$index === formData.actionList.length - 1"
                    @click="handleActionMoveDown(row, $index)"
                  >
                    {{ $t('recipe.moveDown') }}
                  </el-button> -->
                  <el-button text @click="handleActionEdit(row, $index)">
                    {{ $t('public.edit') }}
                  </el-button>
                  <el-button text @click="handleActionDelete(row, $index)">{{
                    $t('public.delete')
                  }}</el-button>
                </template>
              </TableColumn>
            </BaseTable>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- <el-alert title="特别说明：" type="warning" show-icon :closable="false">
      特别说明：请根据对应型号设备认真核对后再修改，避免超出可控范围导致设备损坏！<br />
      若某一项不存在，请设置为0！
    </el-alert> -->
    <template #footer>
      <div class="form-dialog-footer" style="padding-top: 10px">
        <el-button plain @click="handleClose">{{
          $t('public.cancel')
        }}</el-button>
        <el-button type="primary" @click="handleSubmitForm">{{
          $t('public.confirm')
        }}</el-button>
      </div>
    </template>
  </BaseDialog>

  <AddAction
    v-if="addActionVisible"
    v-model="addActionVisible"
    :type="addOrEditType"
    :row="actionRow"
    @add="handleAddActionCb"
    @update="handleUpdateActionCb"
  />
</template>

<script setup>
import AddAction from './AddAction.vue'

const props = defineProps({
  type: {
    type: String,
    default: 'add' // add | edit
  },
  id: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['update'])
const dialogVisible = defineModel({
  type: Boolean,
  default: false
})
const { language } = storeToRefs(useAppStore())
const title = computed(() =>
  props.type === 'add' ? '新建外设信息' : '编辑外设信息'
)

const refDialogForm = ref(null)
const formLoading = ref(false)
const formData = ref({
  model: '',
  type: '',
  name: '',
  tag: '',
  driverId: '',
  actionList: []
})
const rules = {
  model: g_rules.commonInputText(g_t('device.deviceModel')),
  type: g_rules.commonInputText('外设类型'),
  name: g_rules.commonInputText('外设名称'),
  tag: g_rules.commonInputText('外设标签'),
  driverId: g_rules.commonInputText('外设驱动ID'),
  actionList: {
    required: true,
    message: '请添加动作列表',
    trigger: ['blur', 'change']
  }
}
const deviceModelList = ref([])
const peripheralModelList = ref([])
const refContentTable = ref(null)
const tableLoading = ref(false)
const columnWidthObj = ref({})
// 弹框参数
const addActionVisible = ref(false)
const actionRow = ref({})
const addOrEditType = ref('')
const actionTableIndex = ref('')

watch(
  () => formData.value.actionList,
  (nv, ov) => {
    useTableColumnWidth({
      refTable: refContentTable.value
    }).getTableColumnWidth(data => {
      columnWidthObj.value = data
    })
    nextTick(() => {
      refDialogForm.value.validateField(['actionList'])
    })
  },
  {
    deep: true
  }
)

onMounted(() => {
  getQueryModelList()
  getQueryTypeList()
  props.type === 'edit' && getFormData()
})

const getFormData = _ => {
  g_api.device
    .apiPeripheralQueryDetail({ id: props.id })
    .then(({ code, data }) => {
      if (code === '200' && data) {
        formData.value = {
          ...formData.value,
          id: '',
          appId: '',
          tenantId: '',
          status: ''
        }
        g_utils.assignFormData(formData.value, data)
        console.log('formData.value', formData.value)
      }
    })
}

const getQueryModelList = _ => {
  g_api.device
    .apiDeviceQueryModelList()
    .then(({ code, data }) => {
      if (code === '200' && data) {
        // console.log('data', data)
        deviceModelList.value = data.map(item => ({
          value: item,
          label: item
        }))
      }
    })
    .finally(() => {})
}

const getQueryTypeList = _ => {
  g_api.recipe
    .apiDictDropList({
      dictType: 'peripheral_type'
    })
    .then(({ code, data }) => {
      if (code === '200' && data) {
        // console.log('data', data)
        peripheralModelList.value = data
      }
    })
}

const handleClose = _ => {
  dialogVisible.value = false
}

const handleAddAction = _ => {
  addActionVisible.value = true
  addOrEditType.value = 'add'
}

const handleActionMoveUp = (row, i) => {
  const { actionList } = formData.value
  ;[actionList[i - 1], actionList[i]] = [actionList[i], actionList[i - 1]]
}

const handleActionMoveDown = (row, i) => {
  const { actionList } = formData.value
  ;[actionList[i + 1], actionList[i]] = [actionList[i], actionList[i + 1]]
}

const handleActionEdit = (row, i) => {
  addActionVisible.value = true
  actionRow.value = row
  addOrEditType.value = 'edit'
  actionTableIndex.value = i
}

const handleActionDelete = (row, i) => {
  ElMessageBox.confirm(
    `是否删除该菜谱步骤【${row.name}】?`,
    g_t('public.tip'),
    {
      confirmButtonText: g_t('public.confirm'),
      cancelButtonText: g_t('public.cancel'),
      type: 'warning'
    }
  )
    .then(() => {
      formData.value.actionList.splice(i, 1)
    })
    .catch(() => {})
}

const handleAddActionCb = data => {
  console.log('handleAddActionCb', data)
  formData.value.actionList.push(data)
}

const handleUpdateActionCb = data => {
  console.log('handleUpdateActionCb', data)
  formData.value.actionList.splice(actionTableIndex.value, 1, data)
}

const handleSubmitForm = () => {
  if (formLoading.value) return
  refDialogForm.value.validate(valid => {
    console.log('formData.value', formData.value)
    if (!valid) return
    formLoading.value = true
    const urlMethod =
      props.type === 'add'
        ? g_api.device.apiPeripheralCreate
        : g_api.device.apiPeripheralUpdate
    urlMethod(formData.value)
      .then(res => {
        if (res.code === '200') {
          ElMessage({
            message: res.message,
            type: 'success'
          })
          handleClose()
          emit('update')
        }
      })
      .finally(() => {
        formLoading.value = false
      })
  })
}
</script>

<style scoped lang="scss"></style>
